package com.zxy.dept.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxy.base.dto.PageRequest;
import com.zxy.dept.dto.DeptTreeNode;
import com.zxy.dept.entity.Dept;
import com.zxy.dept.mapper.DeptMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

@Service
public class DeptService extends ServiceImpl<DeptMapper,Dept> {

    @Autowired
    private DeptMapper deptMapper;

    public Integer insertDept(Dept dept) {
        int insert = deptMapper.insert(dept);
        return dept.getDeptId();
    }

    public int updateDept(Dept dept) {
        int i = deptMapper.updateById(dept);
        return i;
    }

    public Page<Dept> findDeptByPage(PageRequest<Dept> pageRequest) {

        Page<Dept> page = new Page();
        page.setSize(pageRequest.getSize());
        page.setCurrent(pageRequest.getPageNum());


        Page<Dept> deptPage = deptMapper.selectPage(page, new QueryWrapper<Dept>()
                .lambda().eq(Dept::getDeptName, pageRequest.getRequest().getDeptName()));
        return deptPage;
    }

    public int deleteDept(Dept dept) {
        return deptMapper.deleteById(dept);
    }

    public List<DeptTreeNode> getDeptTreeNodeList() {

        List<Dept> depts = deptMapper.selectList(null);
        List<DeptTreeNode> treeAllNodes = new LinkedList<>();

        for(Dept dept: depts) {
            if(Objects.equals(dept.getParentId(),0)) {
                List<DeptTreeNode> treeNodes = buildDeptTree(dept, depts);
                DeptTreeNode top = new DeptTreeNode(dept.getDeptId(),dept.getDeptName(),
                        dept.getParentId(),treeNodes);
                treeAllNodes.add(top);
            }
        }
        return treeAllNodes;
    }

    private List<DeptTreeNode> buildDeptTree(Dept parent,List<Dept> depts) {
        List<DeptTreeNode> treeNodes = new LinkedList<>();

        for(Dept dept: depts) {
            if(Objects.equals(parent.getDeptId(),dept.getParentId())) {
                DeptTreeNode node = new DeptTreeNode(dept.getDeptId(),dept.getDeptName(),dept.getParentId(),
                        buildDeptTree(dept,depts));
                treeNodes.add(node);
            }
        }
        return treeNodes;

    }

}
